package push

import (
	"encoding/json"
	"fmt"
	"parking-lot-go-dingding/logger"
	"parking-lot-go-dingding/model/cars"
	"parking-lot-go-dingding/model/view"
	"time"

	"github.com/gin-gonic/gin"
)

var dingTalkOutLogger = logger.NewLogger("dingtalk", "out")

func Out(c *gin.Context) {
	requestData := struct {
		ParkName   string `json:"park_name"`
		CarNumber  string `json:"car_number"`
		CarNoColor int    `json:"car_no_color"`
		RegionName string `json:"region_name"`
		OutTime    string `json:"out_time"`
		StopTime   int    `json:"stop_time"`
		Money      int    `json:"money"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestData); err != nil {
		dingTalkEntryLogger.Error("json接收失败")
		return
	}

	dingTalkEntryLogger.Info("方法:车辆出场")
	jsonStr, _ := json.Marshal(requestData)
	dingTalkEntryLogger.Info(string(jsonStr))

	var carsStruct cars.CarsStruct
	carFind, err := carsStruct.Find(map[string]interface{}{
		"car_number":   requestData.CarNumber,
		"car_no_color": requestData.CarNoColor,
	})

	if err != nil {
		dingTalkEntryLogger.Error("车辆信息查询失败")
		return
	}

	var membersDingtalkViewStruct view.MembersDingtalkViewStruct
	memberFind, err := membersDingtalkViewStruct.First(map[string]interface{}{
		"member_id": carFind.MemberId,
	})
	if err != nil {
		dingTalkEntryLogger.Error(fmt.Sprintf("用户信息查询失败,%s", err.Error()))
		return
	}

	//接收消息人
	dingUserId := memberFind.MemberDingtalkUserid
	if memberFind.MemberDingtalkFromUserid != "" {
		dingUserId = memberFind.MemberDingtalkFromUserid
	}

	//模板id
	templateId := "bb03f63f3e81469b8a0c5edb7bdbc0db"

	//时间格式化
	t, err := time.Parse("2006-01-02 15:04:05", requestData.OutTime)
	if err != nil {
		dingTalkEntryLogger.Error(fmt.Sprintf("解析时间失败,%s", err.Error()))
		return
	}

	//拼接模板消息
	parkExt := ""
	if requestData.RegionName != "" {
		parkExt = "(" + requestData.RegionName + ")"
	}
	templateMsg := map[string]interface{}{
		"car_number": requestData.CarNumber,
		"time":       t.Format("2006年01月02日 15时04分"),
		"park_name":  requestData.ParkName + parkExt,
		"stop_time":  formatTime(requestData.StopTime),
		"money":      fmt.Sprintf("%d", requestData.Money/100),
	}

	response, err := sendTemplateMsg(carFind.TripartiteVoucher, templateId, dingUserId, templateMsg)
	if err != nil {
		dingTalkEntryLogger.Error(fmt.Sprintf("接口请求失败,%s", err.Error()))
	}

	dingTalkEntryLogger.Error(fmt.Sprintf("接口返回值,%s", response))
	dingTalkEntryLogger.Error("接口请求成功")
}

func formatTime(minutes int) string {
	if minutes < 0 {
		return "Invalid time"
	}

	days := minutes / (24 * 60)
	hours := (minutes % (24 * 60)) / 60
	remainingMinutes := minutes % 60

	result := ""
	if days > 0 {
		result += fmt.Sprintf("%d天", days)
	}
	if hours > 0 {
		result += fmt.Sprintf("%d小时", hours)
	}
	if remainingMinutes > 0 {
		result += fmt.Sprintf("%d分钟", remainingMinutes)
	}

	return result
}
